/*
 * linkedlist_example.c: Create a linked list and do some things with it.
 */
#include <sharp-linkedlist.h>
#include <sharp-alloc.h>

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int *element1 = sharp_malloc(sizeof(int));
    int *element2 = sharp_malloc(sizeof(int));
    int *element3 = sharp_malloc(sizeof(int));

    sharp_linkedlist *list;
    sharp_linkedlist_init(&list);

    /* Let's insert some elements, numbered for the sake of convenience and
     * simple data types that won't be too interesting otherwise.
     */
    *element1 = 1;
    sharp_linkedlist_append(&list, element1);

    *element2 = 2;
    sharp_linkedlist_append(&list, element2);

    *element3 = 3;
    sharp_linkedlist_append(&list, element3);

    /* Now iterate over the list. We should retrieve them in the same order as
     * we got them. Print them on screen so the user actually sees something
     * happen. Make sure our *node is initialized to NULL so we can iterate
     * starting from the first node.
     */
    sharp_linkedlist *node = NULL;
    while(sharp_linkedlist_iter(list, &node)) {
        printf("%d\n", *(int*)node->data);
    }

    /* The linked list is done for. Let's clean up. the _destroy function also
     * also calls a provided function, which can free up data for structs or
     * unions as necessary before _delete frees the element itself.
     *
     * We use free() as a function to clean up, but usually, you'll want to
     * have an actual function freeing members of your struct as well.
     */
    sharp_linkedlist_destroy(&list, (void*)free);

    return EXIT_SUCCESS;
}

